let Task = require('../model/task')
let Task_sign = require('../model/task_sign')
let User = require('../model/user')
let Session = require('../model/session')
let userController = require('../controller/user')
let result = require('../utils/result')
let format = require('../utils/format.js')
var util = require("util")
let md5 = require('md5')
let axios = require('axios')
function LoginController(){

};
LoginController.prototype.login = async (req,res)=>{
    let code = req.query.code;
    let Inviter = req.query.state;
    var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx838cf54dd030d93a&secret=b7f8aca56652260930307a1597e349ab&code=' + code + '&grant_type=authorization_code'
    axios.get(url).then(rsp=>{
        if(rsp.data !== 40163 && rsp.data.openid){
            let access_token = rsp.data.access_token
            let url2 = 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + rsp.data.openid + '&lang=zh_CN'
            axios.get(url2).then(Result=>{
                User.findOne({where:{openid:Result.data.openid}}).then(user=>{
                    if(user){
                        if(!user.invite_code){
                            let invite_code=md5(Result.uid+Result.openid+new Date().getTime());
                            User.update({invite_code:invite_code},{
                                where:{
                                    openid:Result.data.openid
                                }
                            })
                        };
                        User.update({
                            openid: Result.data.openid,
                            headimgurl:Result.data.headimgurl,
                            nickname:Result.data.nickname
                        },{where:{openid:Result.data.openid}}).then(()=>{
                            User.findOne({where:{openid:Result.data.openid}}).then(user=>{

                                Session.findOne({where:{openid:Result.data.openid}}).then(sess=>{
                                    let access_token = md5(((new Date().getTime()) + user.uid) + user.openid);
                                    if(sess){
                                        Session.update({
                                            openid:user.openid,
                                            access_token:access_token,
                                            exp_time:moment().valueOf()+3600000,
                                        },{where:{uid:user.uid}})
                                    }else{
                                        Session.create({
                                            uid:user.uid,
                                            openid:user.openid,
                                            access_token:access_token,
                                            exp_time:moment().valueOf()+3600000,
                                        })
                                    }

                                    res.status(200).json(result(0,'success',{user:{
                                            uid:user.uid,
                                            headimgurl:user.headimgurl,
                                            nickname:user.nickname,
                                            balance:user.balance,
                                            profit:user.profit,
                                            type:user.type,
                                            openid:user.openid,
                                            invite_code:user.invite_code
                                        },access_token:access_token}))
                                })

                            })
                        })
                    }else{
                        User.create({
                            openid: Result.data.openid,
                            headimgurl:Result.data.headimgurl,
                            nickname:Result.data.nickname,
                            invite_code:md5(Result.uid+Result.openid+new Date().getTime()),
                            Inviter:Inviter
                        }).then(()=>{
                            User.findOne({where:{openid:Result.data.openid}}).then(user=>{
                                Session.findOne({where:{openid:Result.data.openid}}).then(sess=>{
                                    let access_token = md5(new Date().getTime() + user.uid + user.openid);
                                    if(sess){
                                        Session.update({
                                            openid:user.openid,
                                            access_token:access_token,
                                            exp_time:moment().valueOf()+3600000,
                                        },{where:{uid:user.uid}})
                                    }else{
                                        Session.create({
                                            uid:user.uid,
                                            openid:user.openid,
                                            access_token:access_token,
                                            exp_time:moment().valueOf()+3600000,
                                        })
                                    }
                                    res.status(200).json(result(0,'success',{user:{
                                            uid:user.uid,
                                            headimgurl:user.headimgurl,
                                            nickname:user.nickname,
                                            balance:user.balance,
                                            profit:user.profit,
                                            type:user.type,
                                            openid:user.openid,
                                            invite_code:user.invite_code
                                        },
                                        access_token:access_token}))
                                })
                            })
                        });
                    }


                }).catch(err=>{
                    res.status(200).json(result(-1,err))
                })

            }).catch(err=>{
                res.status(200).json(result(-1,err))

            })
        }else {
            res.status(200).json(result(-1,rsp.data.errmsg))

        }

    }).catch(err=>{
        res.status(200).json(result(-1,'fail',err))
    })
}
LoginController.prototype.chekLogin = async (req,res,next)=>{
    let access_token = req.query.access_token;
    let uid = req.query.uid;
    if(!uid){
        res.status(200).json(result(-1,'fail','uid参数'))
        return;
    }
    if(!access_token){
        res.status(200).json(result(-1,'fail','access_token参数'))
        return;
    }
    Session.findOne({where:{uid,access_token}}).then(sess=>{
        if(sess){
            let t = moment(sess.exp_time).valueOf();
            let now = moment().valueOf();
            if(t <=now){
                res.status(200).json(result(1,'token已过期,请重新登录'))
                return;
            }else{
                next()
                // res.status(200).json(result(0,'success',{sess,t:moment().valueOf()}))
            }
        }else{
            res.status(200).json(result(-1,'fail','token不存在'))
            return;
        }
    })
}
let loginController = new LoginController();
module.exports = loginController
